<!--
 * @Description: 添加/修改分类目录时的弹窗
 * @Version: 1.0
 * @Autor: chen_yt
 * @Date: 2020-09-17 19:03:38
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2022-01-20 17:16:30
-->
<template>
  <div class="dialog-for-column">
    <fks-dialog
      v-if="Visible"
      :visible.sync="Visible"
      :append-to-body="true"
      width="960px"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      @close="close"
    >
      <template slot="title">
        <i :class="iconClass" />
        <span>{{ dialogTitle }}</span>
      </template>

      <div class="column-edit">
        <fks-form
          ref="Form"
          :model="Form"
          label-width="84px"
          :disabled="operateType == 'show'"
          :rules="rules"
        >
          <fks-form-item
            :span="24"
            :label="LANG.CATEGORY_NAME"
            prop="categoryName"
          >
            <fks-input
              v-model="Form.categoryName"
              maxlength="50"
              show-word-limit
            />
          </fks-form-item>
          <fks-form-item
            :span="12"
            :label="LANG.REMARK"
            prop="description"
          >
            <fks-input
              v-model="Form.description"
              maxlength="50"
              show-word-limit
            />
          </fks-form-item>

          <fks-form-item
            :span="12"
            :label="LANG.CONTENT_TEMPLATE"
            prop="templateId"
          >
            <fks-select
              v-model="Form.templateId"
              style="width: 100%"
              @change="getTemplateDetail"
            >
              <fks-option
                v-for="item in templateList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </fks-select>
          </fks-form-item>

          <!-- 样例列表 -->
          <fks-form-item
            :span="24"
            :label="LANG.DEMO_LIST"
            prop="demoList"
          >
            <fks-table :data="demoData">
              <fks-table-column
                label="#"
                width="55"
                header-align="center"
                align="center"
              >
                <template slot-scope="scope">
                  <span>{{ scope.$index + 1 }}</span>
                </template>
              </fks-table-column>
              <template v-for="item in templateDetail">
                <template v-if="item.isReveal == '1'">
                  <fks-table-column
                    v-if="item.fieldName == 'TITLE'"
                    :key="item.fieldName"
                    prop="title"
                    align="left"
                    is-link
                    min-width="400"
                    :label="item.alias"
                  >
                    <template slot-scope="scope">
                      <span>{{ scope.row[item.fieldName] }}</span>
                    </template>
                  </fks-table-column>
                  <fks-table-column
                    v-else
                    :key="item.fieldName"
                    :label="item.alias"
                    :prop="item.fieldName"
                    header-align="center"
                    :align="alignDecide(item.fieldName)"
                    :min-width="minWidth(item.fieldName)"
                    :max-width="maxWidth(item.fieldName)"
                  >
                    <template slot-scope="scope">
                      <span>{{ scope.row[item.fieldName] }}</span>
                    </template>
                  </fks-table-column>
                </template>
              </template>
            </fks-table>
          </fks-form-item>
        </fks-form>
      </div>

      <template
        v-if="operateType != 'show'"
        slot="footer"
      >
        <section>
          <fks-button
            type="primary"
            icon="fks-icon-check"
            @click="submit"
          >
            {{ LANG.SAVE }}
          </fks-button>
        </section>
      </template>
    </fks-dialog>
  </div>
</template>

<script>
import { addCategory } from '../../api/index'
import {
  getTemplateList,
  getContentList,
  getTemplateDetailById
} from '@/modules/Content/api'
import {
  defaultField,
  defaultMinLength,
  defaultMaxLength,
  defaultAlign
} from '@/modules/Content/defaultData'
import { demoData } from '../../api/demoData'
export default {
  name: 'AddCategory',
  props: {
    visible: {
      type: Boolean
    },
    operateType: {
      type: String,
      default: 'new'
    },
    categoryInfo: {
      type: Object
    }
  },
  data() {
    return {
      Visible: false,
      Form: {},
      templateList: [],
      templateDetail: []
    }
  },
  computed: {
    demoData() {
      return demoData
    },
    dialogTitle() {
      if (this.operateType == 'new') return this.LANG.ADD
      if (this.operateType == 'edit') return this.LANG.EDIT
      return this.LANG.VIEW
    },
    iconClass() {
      if (this.operateType == 'new') return 'fks-icon-plus'
      if (this.operateType == 'edit') return 'fks-icon-edit'
      return 'fks-icon-view'
    },
    rules() {
      return {
        categoryName: [
          {
            required: true,
            message: this.LANG.ERROR_TEMPLATENAME,
            trigger: 'blur'
          },
          { max: 50, message: this.LANG.ERROR_MAX_50, trigger: 'blur' }
        ],
        description: [
          { max: 50, message: this.LANG.ERROR_MAX_50, trigger: 'blur' }
        ],
        templateId: [
          {
            required: true,
            message: this.LANG.ERROR_NOTEMPLATE,
            trigger: 'blur'
          }
        ]
      }
    }
  },
  watch: {
    visible(val) {
      this.Visible = val
      if (val) {
        this.initData()
      }
    }
  },
  mounted() {
    this.getTemplateList()
  },
  methods: {
    resetData() {
      this.Form = {}
    },
    cancel() {
      this.close()
    },
    close() {
      this.$emit('close')
      this.resetData()
    },

    /**
     * @description: 用于样例列表渲染，决定表格宽度及数据对齐方式
     */
    alignDecide(name) {
      if (defaultAlign[name] == 1) return 'left'
      return 'center'
    },

    minWidth(name) {
      return defaultMinLength[name] ? defaultMinLength[name] : 300
    },
    maxWidth(name) {
      return defaultMaxLength[name] ? defaultMaxLength[name] : ''
    },

    /**
     * @description: 将form处理为与接口对应的形式
     * @param {Object} form 表单的form
     * @return {Object} newForm 用于提交的form
     */
    dealForSubmit(form) {
      let newForm = {
        id: form.id,
        description: form.description,
        categoryName: form.categoryName,
        templateId: form.templateId,
        isHide: form.isHide
      }
      return newForm
    },

    /**
     * @description: 提交处理，判断是否填写完整
     *                当目录下存在内容时，禁止修改模板
     */
    submit() {
      this.$refs['Form'].validate((valid) => {
        if (valid) {
          this.existContent()
        }
        if (!valid) {
          this.$message({
            type: 'error',
            message: this.LANG.ERROR_UNDO_WRITE
          })
          return
        }
      })
    },

    /**
     * @description: 判断目录下是否有内容
     */
    existContent() {
      if (this.operateType == 'edit') {
        if (this.Form.templateId == this.categoryInfo.templateId) {
          this.submitForm()
        } else {
          let temp = {
            page: 1,
            size: 1,
            categoryId: this.Form.id
          }
          getContentList(temp)
            .then((res) => {
              if (res.status) {
                if (res.data) {
                  this.$message({
                    type: 'error',
                    message: this.LANG.ERROR_HASCONTENT_TEMPLATE
                  })
                } else {
                  this.submitForm()
                }
              }
            })
            .catch(() => {})
        }
      } else {
        this.submitForm()
      }
    },

    /**
     * @description: 真正的提交表单方法
     */
    submitForm: async function () {
      let submitForm = this.dealForSubmit(this.Form)
      addCategory(submitForm, this.operateType)
        .then((res) => {
          if (res.status) {
            this.$message({
              type: 'success',
              message:
                this.operateType == 'new'
                  ? this.LANG.ADD_SUCCESS
                  : this.LANG.EDIT_SUCCESS
            })
            this.$emit('submit')
          } else {
            //目录重名时，显示异常
            //后端已抛出异常，前端就不用处理了
            if (res.code == -1) {
              // this.$message({
              //   type: 'error',
              //   message: this.LANG.ERROR_EXIST
              // })
              return
            }
          }
        })
        .catch(() => {})
    },

    /**
     * @description: 初始化Dialog
     *               新增时isHide默认为"显示"状态
     */
    initData() {
      this.resetData()
      if (this.operateType == 'new') {
        this.$set(this.Form, 'templateId', this.templateList[0].id)
        this.$set(this.Form, 'isHide', 0)
      }
      if (this.operateType == 'edit' || this.operateType == 'show') {
        this.Form = JSON.parse(JSON.stringify(this.categoryInfo))
      }
      this.getTemplateDetail(this.Form.templateId)
    },

    getTemplateList() {
      let temp = {
        page: 1,
        size: 3000
      }
      return getTemplateList(temp)
        .then((res) => {
          if (res.status) {
            this.templateList = []
            res.data.templateList.forEach((item) => {
              this.templateList.push({
                name: item.name,
                id: item.id
              })
            })
          }
        })
        .catch(() => {
          this.templateList = []
        })
    },

    /**
     * @description: 获得该分类目录采用的模板细节
     */
    getTemplateDetail(val) {
      this.Form.templateId = val
      let templateId = val

      if (templateId == '' || !templateId) {
        this.templateDetail = defaultField
      } else {
        getTemplateDetailById(templateId)
          .then((res) => {
            if (res.status) {
              this.templateDetail = res.data
            }
          })
          .catch(() => {
            this.templateDetail = []
          })
      }
    }
  }
}
</script>

<style scoped lang="scss">
::v-deep .fks-dialog__body {
  padding-bottom: 0;
}
</style>
